package cn.yuxiaoyuan.util;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author solargen
 * @version 1.0
 * @date 2025/6/22 15:46
 */
@Component
@RefreshScope
public class TxCosUtil {
    @Value("${SecretId}")
    private String SecretId;
    @Value("${SecretKey}")
    private String SecretKey;

    @Value("${RegionName}")
    private String RegionName;
    @Value("${BucketName}")
    private String BucketName;
    @Value("${path}")
    private String path;

    public String upload(MultipartFile file, String fileName) {
        try {
            // 1 初始化用户身份信息（secretId, secretKey）。
            // SECRETID 和 SECRETKEY 请登录访问管理控制台 https://console.cloud.tencent.com/cam/capi 进行查看和管理
            String secretId = SecretId;
            String secretKey = SecretKey;
            COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
            Region region = new Region(RegionName);
            ClientConfig clientConfig = new ClientConfig(region);
            clientConfig.setHttpProtocol(HttpProtocol.https);
            COSClient cosClient = new COSClient(cred, clientConfig);
            // 指定文件上传到 COS 上的路径，即对象键。例如对象键为 folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
            String key = path+fileName;
            PutObjectRequest putObjectRequest = new PutObjectRequest(BucketName, key, file.getInputStream(),new ObjectMetadata());
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            System.out.println(putObjectResult.getDateStr());
            cosClient.shutdown();
            //https://250120-1325252950.cos.ap-guangzhou.myqcloud.com/driver%2Fningguang.png
            return String.format("https://%s.cos.%s.myqcloud.com/%s", BucketName, RegionName, key);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
